<?php
/**
 * Created by PhpStorm.
 * User: daimingkang
 * Date: 2018/9/6
 * Time: 下午7:17
 */

namespace App\Api\Controllers\Mini;


/**微信支付
 * Class IndexController
 * @package App\Api\Controllers\AppletsPay
 */
class WxpayController
{
    private static $instance;

    const SP_MCHID  = '1509500551';
    const SP_APPID  = 'wx4e41b2f311ded3b1';
    const XLID      = '62D80C784D5077AA85051564B46B4912DB65D082';
    const JSAPI_URL = 'https://api.mch.weixin.qq.com/v3/pay/partner/transactions/jsapi';
    const QUERY_URL = 'https://api.mch.weixin.qq.com/v3/pay/partner/transactions/out-trade-no';
    const REFUND    = 'https://api.mch.weixin.qq.com/v3/refund/domestic/refunds';
    const PROFITSHARING = 'https://api.mch.weixin.qq.com/v3/profitsharing/orders';
    const PROFITSHARING_ADD = 'https://api.mch.weixin.qq.com/v3/profitsharing/receivers/add';
    const PROFITSHARING_QUERY = 'https://api.mch.weixin.qq.com/v3/profitsharing/orders';
    const PROFITSHARING_RETURN_ORDERS = 'https://api.mch.weixin.qq.com/v3/profitsharing/return-orders';
    const PROFITSHARING_RETURN_ORDERS_QUERY = 'https://api.mch.weixin.qq.com/v3/profitsharing/return-orders';
    const PROFITSHARING_ORDERS_UNFREEZE = 'https://api.mch.weixin.qq.com/v3/profitsharing/orders/unfreeze';
    const PROFITSHARING_TRANSACTIONS = 'https://api.mch.weixin.qq.com/v3/profitsharing/transactions';
    const PROFITSHARING_DEL = 'https://api.mch.weixin.qq.com/v3/profitsharing/receivers/delete';

    const CERT = 'https://pay.zgjindoufu.com/upload/images/186055811861601389159.pem';

    public static function getInstance ()
    {
        if (! isset(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function build($data, $url, $types='POST')
    {

        $params = $types == 'POST' ? json_encode($data) : '';

        $url_parts     = parse_url($url);
        $timeStamp     = time();
        $noncestr      = $this->getNoncestr();
        $canonical_url = ($url_parts['path'] . (!empty($url_parts['query']) ? "?${url_parts['query']}" : ""));
        $key           = $this->getSign($params,$canonical_url,$noncestr,$timeStamp, $types);//签名
        $token         = sprintf('mchid="%s",serial_no="%s",nonce_str="%s",timestamp="%d",signature="%s"',
            self::SP_MCHID,self::XLID,$noncestr,$timeStamp,$key);//头部信息

        $header  = array(
            'Content-Type:'.'application/json; charset=UTF-8',
            'Accept:application/json',
            'User-Agent:*/*',
            'Authorization: WECHATPAY2-SHA256-RSA2048 '.$token
        );
        if ($types == 'GET') {
            return $this->curl_get_https($url,$data,$header);
        }
        return $this->curl_post_https($url,$data,$header);
    }

    //微信支付签名
    public function getSign($data=array(),$url,$randstr,$time,$typs='POST')
    {
        $str = $typs."\n".$url."\n".$time."\n".$randstr."\n".$data."\n";
        $key = file_get_contents(self::CERT);//在商户平台下载的秘钥
        $str = $this->getSha256WithRSA($str,$key);
        return $str;
    }

    public function getNoncestr($length = 32) {

        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str ="";
        for ( $i = 0; $i < $length; $i++ )  {
            $str.= substr($chars, mt_rand(0, strlen($chars)-1), 1);
        }
        return $str;
    }

    //调起支付的签名
    public function getWechartSign($appid,$timeStamp,$noncestr,$prepay_id){
        $str = $appid."\n".$timeStamp."\n".$noncestr."\n".$prepay_id."\n";
        $key = file_get_contents(self::CERT);//在商户平台下载的秘钥
        $str = $this->getSha256WithRSA($str,$key);
        return $str;
    }

    public function getSha256WithRSA($content, $privateKey){
        $binary_signature = "";
        $algo = "SHA256";
        openssl_sign($content, $binary_signature, $privateKey, $algo);
        $sign = base64_encode($binary_signature);
        return $sign;
    }

    public function curl_get_https($url,$data,$header){ // 模拟提交数据函数
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);// 头部信息
        $tmpInfo = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            return 'Errno'.curl_error($curl);//捕抓异常
        }
        curl_close($curl); // 关闭CURL会话
        return $tmpInfo; // 返回数据，json格式
    }
    /* PHP CURL HTTPS POST */
    public function curl_post_https($url,$data,$header){ // 模拟提交数据函数
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data)); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回

        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        $tmpInfo = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            echo 'Errno'.curl_error($curl);//捕抓异常
        }
        curl_close($curl); // 关闭CURL会话
        return $tmpInfo; // 返回数据，json格式
    }



}